//
//  AppDelegate.m
//  ZDSC
//
//  Created by ZDTX on 2021/5/12.
//

#import "AppDelegate.h"
#import "ZYCNavigationController.h"
#import "ZYCMainViewController.h"
#import <IQKeyboardManager.h>
#import "ZYCLoginViewController.h"
#import <GTSDK/GeTuiSdk.h>
#import "ThirdMacro.h"
#import <SJVideoPlayer.h>

//#import <Bugly/Bugly.h>

/*
 
 APP收到推送调用方法：
 
                            iOS8、iOS9                                iOS10及以上系统
 点击推送启动APP           调用function 1及function 2                 调用function 1及function 4
 APP在前台收到推送         调用function 2                             调用function 3
 APP在前台点击推送         调用function 2                             调用function 4
 APP在后台点击推送         调用function 2                             调用function 4
 
 */

//GeTuiSdkDelegate
@interface AppDelegate ()<UIApplicationDelegate>

@end

@implementation AppDelegate

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    return UIInterfaceOrientationMaskAll;
}


#pragma mark - function 1
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    UIViewController *vc;
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"kLoginFlag"]) {
        vc = [[ZYCNavigationController alloc] initWithRootViewController:[[ZYCLoginViewController alloc] init]];
    }else{
        vc = [[ZYCMainViewController alloc] init];
    }
    self.window.rootViewController = vc;
    [self.window makeKeyAndVisible];
    
    //集成个推推送
    [self configGeTui];
    
    
    [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
    
    //强制关闭深色模式
    #if defined (__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0
        if(@available(iOS 13.0,*)){
            self.window.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
        }
    #endif
    [self configIQKeyboardManager];
    
    // 检测版本更新
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"kLoginFlag"]) {
        [self checkVersionUpdate];
        [self postClientId];
    }
    // 集成Bugly
//    [Bugly startWithAppId:kBuglyId];
    // 监控网络
//    [self monitorNetWorkState];
    

    
//    [[TUIKit sharedInstance] setupWithAppId:SDKAPPID logLevel:V2TIM_LOG_NONE];
    
    //
//    [self configRemoteNotofication:application];
    
//    TUIKitConfig *config = [TUIKitConfig defaultConfig];
//    config.defaultAvatarImage = [UIImage imageNamed:@"Doge"];
    
    return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application{
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
//    [GeTuiSdk setBadge:0];
}

// 注册个推ClientId
- (void)postClientId{
    NSDictionary *params = @{
        @"clientId":[[NSUserDefaults standardUserDefaults] objectForKey:@"kClientId"],
        @"appid":kGtAppId,
        @"appkey":kGtAppKey,
        @"brand":@"ios"
    };
    [[URLManager sharedURLManager] postUrlString:Login_GET_GTClientInfo requestService:RequestServiceMessage parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                NSLog(@"保存客户端和角色的关联信息成功");
            }
        } failure:^(NSError * _Nonnull error) {

        }];

}



// 验证版本
- (void)checkVersionUpdate{
       NSString *locationVersion = [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] stringByReplacingOccurrencesOfString:@"." withString:@""];
    [[URLManager sharedURLManager] getUrlString:Common_Get_VersionManager requestService:RequestServiceWorkBench parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                if ([responseObject[@"body"] isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *resultDict = responseObject[@"body"];
                    NSString *currentVersion =  resultDict[@"versionNumber"];
                    currentVersion = [currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
                    if ([currentVersion  integerValue] > [locationVersion integerValue]){// 有版本可更新
                        //是否强制更新（1-是，2-否）
                        if ([resultDict[@"changeUpdate"] integerValue] == 1) {
                            [self mustUpdate];
                        }else{
                            [self optionUpdateWithVersion:resultDict[@"versionNumber"]];
                        }
                    }
           
                }
         
            }
        } failure:^(NSError * _Nonnull error) {

        }];
}

- (void)exitApplication {
    [UIView animateWithDuration:0.3f animations:^{
        self.window.alpha = 0;
        self.window.frame = CGRectMake(0, self.window.bounds.size.width, 0, 0);
    } completion:^(BOOL finished) {
        exit(0);
    }];
    
}
- (void)mustUpdate{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"更新提示" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *mustUpdateAction = [UIAlertAction actionWithTitle:@"前往更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString *urlStr = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=%@", kAppId];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",urlStr]]];
    }];
    [alertController addAction:mustUpdateAction];
    UIAlertAction *notUpdateAction = [UIAlertAction actionWithTitle:@"退出程序" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self exitApplication];
    }];
    [alertController addAction:notUpdateAction];
    [[[UIApplication sharedApplication] keyWindow].rootViewController presentViewController:alertController animated:YES completion:nil];
    
}

- (void)optionUpdateWithVersion:(NSString *)version{
    NSString *ignoreVersionCode = [[NSUserDefaults standardUserDefaults] objectForKey:@"ignoreVersionCode"];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"更新提示" message:nil preferredStyle:UIAlertControllerStyleAlert];
    if (![ignoreVersionCode isEqualToString:version]) {
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"前往更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSString *urlStr = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=%@", kAppId];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",urlStr]]];
        }];
        [alertController addAction:okAction];
        UIAlertAction *nextAction = [UIAlertAction actionWithTitle:@"下次再说" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertController addAction:nextAction];
        UIAlertAction *noTipAction = [UIAlertAction actionWithTitle:@"不再提示" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%@",version] forKey:@"ignoreVersionCode"];
        }];
        [alertController addAction:noTipAction];
        [[[UIApplication sharedApplication] keyWindow].rootViewController presentViewController:alertController animated:YES completion:nil];
    }
    
}
#pragma mark - GeTuiSdkDelegate

/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    //个推SDK已注册，返回clientId
    NSLog(@"\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);
    [[NSUserDefaults standardUserDefaults] setObject:clientId forKey:@"kClientId"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}




//MARK: - 通知回调

/// 通知展示（iOS10及以上版本）
/// @param center center
/// @param notification notification
/// @param completionHandler completionHandler
- (void)GeTuiSdkNotificationCenter:(UNUserNotificationCenter *)center
           willPresentNotification:(UNNotification * )notification
             completionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
__API_AVAILABLE(macos(10.14), ios(10.0), watchos(3.0), tvos(10.0)){
    NSString *msg = [NSString stringWithFormat:@"[ TestDemo ] [APNs] %@ \n%@", NSStringFromSelector(_cmd), notification.request.content.userInfo];
    NSLog(@"*****通知展示:%@",msg);
    completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);

}

 
/// 收到通知信息
/// @param userInfo apns通知内容
/// @param center UNUserNotificationCenter（iOS10及以上版本）
/// @param response UNNotificationResponse（iOS10及以上版本）
/// @param completionHandler 用来在后台状态下进行操作（iOS10以下版本）
- (void)GeTuiSdkDidReceiveNotification:(NSDictionary *)userInfo
                    notificationCenter:(nullable UNUserNotificationCenter *)center
                              response:(nullable UNNotificationResponse *)response
                fetchCompletionHandler:(nullable void (^)(UIBackgroundFetchResult))completionHandler{
    NSString *msg = [NSString stringWithFormat:@"[ TestDemo ] [APNs] %@ \n%@", NSStringFromSelector(_cmd), userInfo];
    NSLog(@"*****收到通知消息:%@",msg);
    if(completionHandler) {
           // [ 参考代码，开发者注意根据实际需求自行修改 ] 根据APP需要自行修改参数值
           completionHandler(UIBackgroundFetchResultNoData);
       }
}


/// 收到透传消息
/// @param userInfo    推送消息内容
/// @param fromGetui   YES: 个推通道  NO：苹果apns通道
/// @param offLine     是否是离线消息，YES.是离线消息
/// @param appId       应用的appId
/// @param taskId      推送消息的任务id
/// @param msgId       推送消息的messageid
/// @param completionHandler 用来在后台状态下进行操作（通过苹果apns通道的消息 才有此参数值）
- (void)GeTuiSdkDidReceiveSlience:(NSDictionary *)userInfo
                        fromGetui:(BOOL)fromGetui
                          offLine:(BOOL)offLine
                            appId:(nullable NSString *)appId
                           taskId:(nullable NSString *)taskId
                            msgId:(nullable NSString *)msgId
           fetchCompletionHandler:(nullable void (^)(UIBackgroundFetchResult))completionHandler{
    // [ GTSDK ]：汇报个推自定义事件(反馈透传消息)，开发者可以根据项目需要决定是否使用, 非必须
    // [GeTuiSdk sendFeedbackMessage:90001 andTaskId:taskId andMsgId:msgId];
    NSString *msg = [NSString stringWithFormat:@"[ TestDemo ] [APN] %@ \nReceive Slience: fromGetui:%@ appId:%@ offLine:%@ taskId:%@ msgId:%@ userInfo:%@ ", NSStringFromSelector(_cmd), fromGetui ? @"个推消息" : @"APNs消息", appId, offLine ? @"离线" : @"在线", taskId, msgId, userInfo];
    NSLog(@"*****收到透传消息:%@",msg);
    
    if([UIApplication sharedApplication].applicationState == UIApplicationStateActive){ //前台
        NSLog(@"应用处于活跃状态");
    }else if([UIApplication sharedApplication].applicationState == UIApplicationStateBackground){
        NSLog(@"应用处于后台");
    }else{
        NSLog(@"应用处于非活跃状态");
    }

    // 透传消息
    [[NSNotificationCenter defaultCenter] postNotificationName:@"kPenetrateMessage" object:userInfo];
    if(completionHandler) {
        // [ 参考代码，开发者注意根据实际需求自行修改 ] 根据APP需要自行修改参数值
        completionHandler(UIBackgroundFetchResultNewData);
    }
}

- (void)GeTuiSdkNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification {
    // [ 参考代码，开发者注意根据实际需求自行修改 ] 根据APP需要自行修改参数值
}

- (void)GeTuiSdkDidOccurError:(NSError *)error {
    NSString *msg = [NSString stringWithFormat:@"[ TestDemo ] [GeTuiSdk GeTuiSdkDidOccurError]:%@\n\n",error.localizedDescription];
    // SDK发生错误时，回调异常错误信息
    NSLog(@"SDK发生错误:%@", msg);
}



- (void)configIQKeyboardManager{
    [IQKeyboardManager sharedManager].enable = YES;
    //工具条
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    //点击背景收回键盘
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [IQKeyboardManager sharedManager].toolbarDoneBarButtonItemText = @"完成";
    [IQKeyboardManager sharedManager].toolbarTintColor= [UIColor blackColor];
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 5.0f;
}


#pragma mark- 监听网络状态
/** 监听网络状态*/
- (void)monitorNetWorkState
{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        //当前网络状态改变时调用
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:{
                NSLog(@"未知网络");
                [MrjToast makeToast:@"未知网络" makeView:[UIApplication sharedApplication].keyWindow];
                break;
            }
            case AFNetworkReachabilityStatusNotReachable:{
                NSLog(@"当前没有网络");
                [MrjToast makeToast:@"当前没有网络" makeView:[UIApplication sharedApplication].keyWindow];
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWWAN:{
                NSLog(@"移动网络");
                [MrjToast makeToast:@"移动网络" makeView:[UIApplication sharedApplication].keyWindow];
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWiFi:{
                NSLog(@"WiFi网络");
                [MrjToast makeToast:@"WiFi网络" makeView:[UIApplication sharedApplication].keyWindow];
                break;
            }
            default:
                break;
        }
    }];
    
    //开始监控
    [manager startMonitoring];
}

- (void)configGeTui{
    dispatch_async(dispatch_get_main_queue(), ^{
        // 通过个推平台分配的appId、 appKey 、appSecret 启动SDK，注：该方法需要在主线程中调用
        [GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self];
        // 注册远程通知
        if (@available(iOS 10.0, *)) {
            [GeTuiSdk registerRemoteNotification: (UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge)];
        } else {
            // Fallback on earlier versions
        }
        
    });
}

@end

#pragma mark -

#warning Configuring rotation control. 请配置旋转控制!

@implementation UIViewController (RotationControl)
///
/// 控制器是否可以旋转
///
- (BOOL)shouldAutorotate {
    // iPhone的demo用到了播放器的旋转, 这里返回NO, 除播放器外, 项目中的其他视图控制器都禁止旋转
    if ( UIUserInterfaceIdiomPhone == UI_USER_INTERFACE_IDIOM() ) {
        return NO;
    }
    
    // iPad的demo未用到播放器的旋转, 这里返回YES, 允许所有控制器旋转
    else if ( UIUserInterfaceIdiomPad == UI_USER_INTERFACE_IDIOM() ) {
        return YES;
    }
    
    // 如果你的项目仅支持竖屏, 可以直接返回NO, 无需进行上述的判断区分.
    return NO;
}

///
/// 控制器旋转支持的方向
///
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    // 此处为设置 iPhone demo 仅支持竖屏的方向
    if ( UIUserInterfaceIdiomPhone == UI_USER_INTERFACE_IDIOM() ) {
        return UIInterfaceOrientationMaskPortrait;
    }
    
    // 此处为设置 iPad demo 仅支持横屏的方向
    else if ( UIUserInterfaceIdiomPad == UI_USER_INTERFACE_IDIOM() ) {
        return UIInterfaceOrientationMaskLandscape;
    }
    
    // 如果你的项目仅支持竖屏, 可以直接返回UIInterfaceOrientationMaskPortrait, 无需进行上述的判断区分.
    return UIInterfaceOrientationMaskPortrait;
}

@end


@implementation UITabBarController (RotationControl)
- (UIViewController *)sj_topViewController {
    if ( self.selectedIndex == NSNotFound )
        return self.viewControllers.firstObject;
    return self.selectedViewController;
}

- (BOOL)shouldAutorotate {
    return [[self sj_topViewController] shouldAutorotate];
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return [[self sj_topViewController] supportedInterfaceOrientations];
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return [[self sj_topViewController] preferredInterfaceOrientationForPresentation];
}
@end

@implementation UINavigationController (RotationControl)
- (BOOL)shouldAutorotate {
    return self.topViewController.shouldAutorotate;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return self.topViewController.supportedInterfaceOrientations;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return self.topViewController.preferredInterfaceOrientationForPresentation;
}

- (nullable UIViewController *)childViewControllerForStatusBarStyle {
    return self.topViewController;
}

- (nullable UIViewController *)childViewControllerForStatusBarHidden {
    return self.topViewController;
}

@end
